<template>
  <div>
    <!-- <h1>用户管理页面</h1> -->
    <!-- :data="users" -->
    <el-button
      type="primary"
      style="margin-top: 10px; margin-left: 10px; margin-bottom: 5px"
      @click="dialogFormVisible = true"
      >添加用户</el-button
    >
    <el-button type="danger" @click="deleteSelectedUsers">批量删除</el-button>
    <el-table
      :data="paginatedUsers"
      style="width: 100%"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" show-overflow-tooltip></el-table-column>
      <el-table-column
        prop="username"
        label="用户名"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="account"
        label="账号"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="phone"
        label="电话"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column prop="locked" label="是否锁定" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-tag :type="scope.row.locked ? 'danger' : 'success'">
            {{ scope.row.locked ? "是" : "否" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" >
        <template slot-scope="scope">
          <el-button @click="editUser(scope.row)" type="primary" size="small"
            >编辑</el-button
          >
          <el-button @click="deleteUser(scope.row)" type="danger" size="small"
            >删除</el-button
          >
          <el-button
            @click="resetPassword(scope.row)"
            type="warning"
            size="small"
            >重置密码</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="bottom"
      background
      layout="prev, pager, next, jumper"
      :current-page.sync="currentPage"
      :page-size="pageSize"
      :total="users.length"
      @current-change="handlePageChange"
    ></el-pagination>

    <!-- <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
      <el-form :model="newUser" ref="newUserForm" :rules="newUserRules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="newUser.username"></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model="newUser.account"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="newUser.password"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="newUser.phone"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="newUser.sex" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否锁定" prop="locked">
          <el-select v-model="newUser.locked" placeholder="请选择是否锁定">
            <el-option label="是" :value="true"></el-option>
            <el-option label="否" :value="false"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddUser">确定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="编辑用户" :visible.sync="dialogEditFormVisible">
      <el-form :model="editingUser" ref="editUserForm" :rules="editUserRules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editingUser.username"></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model="editingUser.account"></el-input>
        </el-form-item>
   
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editingUser.phone"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="editingUser.sex" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否锁定" prop="locked">
          <el-select v-model="editingUser.locked" placeholder="请选择是否锁定">
            <el-option label="是" :value="true"></el-option>
            <el-option label="否" :value="false"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogEditFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdateUser">确定</el-button>
      </span>
    </el-dialog> -->

    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
      <el-form
        :model="newUser"
        ref="newUserForm"
        :rules="newUserRules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="4">
            <el-form-item label="用户名" prop="username"></el-form-item>
          </el-col>
          <el-col :span="14">
            <el-input v-model="newUser.username"></el-input>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            <el-form-item label="账号" prop="account"></el-form-item>
          </el-col>
          <el-col :span="14">
            <el-input v-model="newUser.account"></el-input>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            <el-form-item label="密码" prop="password"></el-form-item>
          </el-col>
          <el-col :span="14">
            <el-input type="password" v-model="newUser.password"></el-input>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            <el-form-item label="电话" prop="phone"></el-form-item>
          </el-col>
          <el-col :span="14">
            <el-input v-model="newUser.phone"></el-input>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            <el-form-item label="性别" prop="sex"></el-form-item>
          </el-col>
          <el-col :span="14">
            <el-select v-model="newUser.sex" placeholder="请选择性别">
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            <el-form-item label="是否锁定" prop="locked"></el-form-item>
          </el-col>
          <el-col :span="14">
            <el-select v-model="newUser.locked" placeholder="请选择是否锁定">
              <el-option label="是" :value="true"></el-option>
              <el-option label="否" :value="false"></el-option>
            </el-select>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddUser">确定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog title="编辑用户" :visible.sync="dialogEditFormVisible">
      <el-form
        :model="editingUser"
        ref="editUserForm"
        :rules="editUserRules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="4">
            <el-form-item label="用户名" prop="username"></el-form-item>
          </el-col>
          <el-col :span="14">
            <el-input v-model="editingUser.username"></el-input>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            <el-form-item label="账号" prop="account"></el-form-item>
          </el-col>
          <el-col :span="14">
            <el-input v-model="editingUser.account"></el-input>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            <el-form-item label="电话" prop="phone"></el-form-item>
          </el-col>
          <el-col :span="14">
            <el-input v-model="editingUser.phone"></el-input>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            <el-form-item label="性别" prop="sex"></el-form-item>
          </el-col>
          <el-col :span="14">
            <el-select v-model="editingUser.sex" placeholder="请选择性别">
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            <el-form-item label="是否锁定" prop="locked"></el-form-item>
          </el-col>
          <el-col :span="14">
            <el-select
              v-model="editingUser.locked"
              placeholder="请选择是否锁定"
            >
              <el-option label="是" :value="true"></el-option>
              <el-option label="否" :value="false"></el-option>
            </el-select>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogEditFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdateUser">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="重置密码" :visible.sync="dialogResetPasswordVisible">
      <el-form
        :model="resettingUser"
        ref="resetPasswordForm"
        :rules="resetPasswordRules"
      >
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            type="password"
            v-model="resettingUser.newPassword"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogResetPasswordVisible = false">取消</el-button>
        <el-button type="primary" @click="handleResetPassword">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Message } from "element-ui";

export default {
  name: "UserManagement",
  data() {
    return {
      users: [],
      paginatedUsers: [],
      selectedUsers: [],
      currentPage: 1,
      pageSize: 8,
      dialogFormVisible: false,
      dialogEditFormVisible: false,
      dialogResetPasswordVisible: false,
      newUser: {
        username: "",
        account: "",
        password: "",
        phone: "",
        sex: "",
        locked: false,
      },
      editingUser: {
        username: "",
        account: "",
        password: "",
        phone: "",
        sex: "",
        locked: false,
      },
      resettingUser: {
        id: null,
        username: "",
        account: "",
        phone: "",
        sex: "",
        locked: false,
        newPassword: "",
      },
      editingUserIndex: null,
      newUserRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        account: [{ required: true, message: "请输入账号", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        phone: [{ required: true, message: "请输入电话", trigger: "blur" }],
        sex: [{ required: true, message: "请选择性别", trigger: "change" }],
        locked: [
          { required: true, message: "请选择是否锁定", trigger: "change" },
        ],
      },
      editUserRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        account: [{ required: true, message: "请输入账号", trigger: "blur" }],
        phone: [{ required: true, message: "请输入电话", trigger: "blur" }],
        sex: [{ required: true, message: "请选择性别", trigger: "change" }],
        locked: [
          { required: true, message: "请选择是否锁定", trigger: "change" },
        ],
      },
      resetPasswordRules: {
        newPassword: [
          { required: true, message: "请输入新密码", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    getUserList() {
      this.$api
        .userList()
        .then((response) => {
          if (response.data.code === 0) {
            this.users = response.data.data;
            this.handlePageChange(this.currentPage);
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    handlePageChange(page) {
      this.currentPage = page;
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.paginatedUsers = this.users.slice(start, end);
    },
    handleAddUser() {
      this.$refs.newUserForm.validate((valid) => {
        if (valid) {
          this.addUser();
        } else {
          console.log("校验失败");
          return false;
        }
      });
    },
    handleUpdateUser() {
      this.$refs.editUserForm.validate((valid) => {
        if (valid) {
          this.updateUser();
        } else {
          console.log("校验失败");
          return false;
        }
      });
    },
    handleResetPassword() {
      this.$refs.resetPasswordForm.validate((valid) => {
        if (valid) {
          this.confirmResetPassword();
        } else {
          console.log("校验失败");
          return false;
        }
      });
    },
    addUser() {
      this.$api
        .addUserinfo(this.newUser)
        .then((response) => {
          if (response.data.code === 0) {
            // this.users.push({ ...this.newUser });
            console.log("users", this.users);
            // this.users.push({ ...response.data.data }); // 使用API返回的数据更新users列表
            // this.handlePageChange(this.currentPage); // 更新分页数据
            this.getUserList();
            this.dialogFormVisible = false;
            Message({
              message: "用户添加成功",
              type: "success",
            });
            this.newUser = {
              username: "",
              account: "",
              password: "",
              phone: "",
              sex: "",
              locked: false,
            };
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    editUser(user) {
      this.editingUserIndex = this.users.indexOf(user);
      this.editingUser = { ...user, password: "" }; // 清空密码字段，避免密码泄露
      this.dialogEditFormVisible = true;
    },
    updateUser() {
      this.$api
        .editUserinfo(this.editingUser)
        .then((response) => {
          if (response.data.code === 0) {
            this.$set(this.users, this.editingUserIndex, {
              ...this.editingUser,
            });
            // this.handlePageChange(this.currentPage); // 更新分页数据
            this.getUserList();
            this.dialogEditFormVisible = false;
            Message({
              message: "用户修改成功",
              type: "success",
            });
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    deleteUser(user) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const index = this.users.indexOf(user);
          console.log("index", index);
          this.$api
            .deleteUser(index)
            .then((response) => {
              if (response.data.code === 0) {
                // this.users.splice(index, 1);
                // this.handlePageChange(this.currentPage); // 更新分页数据
                this.getUserList();
                Message({
                  message: "用户删除成功",
                  type: "success",
                });
              }
            })
            .catch((error) => {
              console.log(error);
            });
        })
        .catch(() => {
          Message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleSelectionChange(val) {
      this.selectedUsers = val;
    },
    deleteSelectedUsers() {
      if (this.selectedUsers.length === 0) {
        Message({
          message: "请选择要删除的用户",
          type: "warning",
        });
        return;
      }

      this.$confirm("此操作将永久删除选中的用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const ids = this.selectedUsers.map((user) => user.id);
          console.log("ids", ids);

          this.$api
            .batchDeleteUser(ids)
            .then((response) => {
              if (response.data.code === 0) {
                // this.users = this.users.filter(user => !ids.includes(user.id));
                // this.handlePageChange(this.currentPage); // 更新分页数据
                this.getUserList();
                Message({
                  message: "批量删除成功",
                  type: "success",
                });
              }
            })
            .catch((error) => {
              console.log(error);
            });
        })
        .catch(() => {
          Message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    resetPassword(user) {
      this.resettingUser = { ...user, newPassword: "" };
      this.dialogResetPasswordVisible = true;
    },
    confirmResetPassword() {
      const user = {
        ...this.resettingUser,
        password: this.resettingUser.newPassword,
      };
      delete user.newPassword;
      this.$api
        .updatePwd(user)
        .then((response) => {
          if (response.data.code === 0) {
            this.dialogResetPasswordVisible = false;
            Message({
              message: "密码重置成功",
              type: "success",
            });
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
  },
};
</script>

<style scoped>
.bottom{
  text-align: right;
}
</style>
